package im.vinci.server.common.tmsg;

import com.aliyun.openservices.ons.api.Message;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import im.vinci.server.utils.JsonUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class MessageSerialization {

    public static String serialize(Message msg) {
        if (msg == null) {
            return "{}";
        }
        ObjectNode userPropertiesNode = JsonNodeFactory.instance.objectNode();
        for (Map.Entry entry: msg.getUserProperties().entrySet()) {
            userPropertiesNode.put(entry.getKey().toString(), entry.getValue().toString());
        }
        ObjectNode ob = JsonNodeFactory.instance.objectNode()
                .put("id",msg.getMsgID())
                .put("topic",msg.getTopic())
                .put("tag",msg.getTag());
        ob.set("userProperties", userPropertiesNode);
        ob.put("body",msg.getBody());
        return JsonUtils.encode(ob);
    }

    public static Message deserialize(String json) {
        if (json == null) {
            return null;
        }
        JsonNode root = JsonUtils.decode(json);
        if (root == null || !root.hasNonNull("id")) {
            return null;
        }
        Message message = new Message();
        message.setMsgID(root.get("id").asText());
        message.setTopic(root.get("topic").asText());
        message.setTag(root.get("tag").asText());
        try {
            message.setBody(root.get("body").binaryValue());
        } catch (IOException e) {
            //ignore
            e.printStackTrace();
        }
        JsonNode userProperties = root.get("userProperties");
        if(userProperties != null && userProperties.isObject()) {
            Iterator<String> iterator =  userProperties.fieldNames();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = userProperties.get(key).asText();
                message.putUserProperties(key,value);
            }
        }
        return message;
    }
}